import {Component, ViewChild, DoCheck, Pipe, PipeTransform} from '@angular/core';

import {NavController, ModalController, AlertController, Platform, ActionSheetController, LoadingController} from 'ionic-angular';

import {Storage} from '@ionic/storage';

import {Common} from "../../../providers/common";
import {Config} from "../../../providers/config";

import _ from "lodash";
import {Content} from 'ionic-angular';
import {CoinService} from "./coin.service";
import {IpmCirculateModal} from "../circulate/circulate.modal";
import {FieldColumnModel} from "./field.column.model";
import {IpmColumnModal} from "./column.modal";
import {IpmCoinFilterModal} from "./filter.modal";
import {IpmCoinDeleteModal} from "./delete.modal";
import {IpmCoinSaveSceneModal} from "./saveScene.modal";
import {StatusBar} from "@ionic-native/status-bar";

@Component({
  selector: 'page-ipm-coin',
  templateUrl: 'coin.html',
  providers: [CoinService]
})
export class IpmCoinPage implements DoCheck {

  ngDoCheck() {

  }

	moa_page_name: any = "page-ipm-coin";
  moa_page_explain: any = "货币基金试算";

  @ViewChild(Content) content: Content;

  items = [0];

  r = "0.01";

  // 列表数据
  listData: any = null;

  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

  hisDays = 20;
  baseValue = 1000;

  showQueryParams = false;
  showQueryCondition = true;

  maxDate = "";

  queryCondition = null;

  selectedFund = [];
  fundCode = "";

  userInfo = null;

  resultType = "TrialCalculationResult";

  ignoreFormatNumberField = ["vc_trial_no", "l_date", "c_portfolio_type", "l_portfolio_no", "l_subfund_no"];

  fieldColumnModel = new FieldColumnModel();

  structuredFund_ShowAllDate = false;

  filterPositionCondition = null;

  sortCondition = null;

  simulatedSceneList = [];

  showByLandscape = false;

  contentWidth = 0;
  fundLeftHeight = 0;
  fundRightHeight = 0;

  scrollContentMarginTop = "";
  requestLoading = {
    "positionTrial": false,
    "simulatedScene": false
  };

  constructor(public navCtrl: NavController,
              public common: Common,
              private coinService: CoinService,
              public modalCtrl: ModalController,
              public alertCtrl: AlertController,
              public actionSheetCtrl: ActionSheetController,
              public config: Config,
              public  plt: Platform,
              private statusBar: StatusBar,
              public storage: Storage,
              private loadingCtrl: LoadingController,) {

    this.coinService.getCoinColumns().subscribe(columns => {
      console.log("getCoinColumns", columns);
      this.fieldColumnModel.entity = columns;

      this.storage.get("CustomFieldColumns").then(CustomFieldColumns => {
        console.log(CustomFieldColumns);
        if (CustomFieldColumns) {
          if (CustomFieldColumns.TrialCalculationResult) {
            //初始化试算结果需要显示的字段
            _.forEach(this.fieldColumnModel["entity"]["TrialCalculationResult"]["fieldColumns"], fieldCol => {
              let temp = _.find(CustomFieldColumns.TrialCalculationResult, {fieldName: fieldCol.fieldName});
              if (temp) {
                fieldCol.isShow = temp["isShow"];
              }
            });
          }

          if (CustomFieldColumns.StructuredFundTrialCalculationResult) {
            //初始化分级基金试算结果需要显示的字段
            _.forEach(this.fieldColumnModel["entity"]["StructuredFundTrialCalculationResult"]["fieldColumns"], fieldCol => {
              let temp = _.find(CustomFieldColumns.StructuredFundTrialCalculationResult, {fieldName: fieldCol.fieldName});
              if (temp) {
                fieldCol.isShow = temp["isShow"];
              }
            });
          }

          if (CustomFieldColumns.PositionTrialCalculationResult) {
            //初始化持仓分析需要显示的字段
            _.forEach(this.fieldColumnModel["entity"]["PositionTrialCalculationResult"]["fieldColumns"], fieldCol => {
              let temp = _.find(CustomFieldColumns.PositionTrialCalculationResult, {fieldName: fieldCol.fieldName});
              if (temp) {
                fieldCol.isShow = temp["isShow"];
              }
            });
          }

          if (CustomFieldColumns.SimulatedSceneList) {
            //初始化模拟情景需要显示的字段
            _.forEach(this.fieldColumnModel["entity"]["SimulatedSceneList"]["fieldColumns"], fieldCol => {
              let temp = _.find(CustomFieldColumns.SimulatedSceneList, {fieldName: fieldCol.fieldName});
              if (temp) {
                fieldCol.isShow = temp["isShow"];
              }
            });
          }
        }
      });

    });

    this.initSimulatedSceneList();
    this.initListData();
    this.initQueryCondition();
    this.initFilterPositionCondition();
    this.initSortCondition();


    /*this.coinService.testFTS_001_0010().subscribe(testFTS_001_0010 => {
      console.log("-------测试FTS_001_0010服务----------", testFTS_001_0010);
    });*/

  }

  ionViewDidLoad() {
    this.content.ionScroll.subscribe(($event: any) => {
      this.initDataGrid();
      /*switch (this.resultType) {
        case "TrialCalculationResult":
          this.initDataGrid();
          break;
      }*/
    });

    this.contentWidth = this.content.getContentDimensions().contentWidth;

    /*document.getElementById("fundLeft").onscroll = function () {
      document.getElementById("fundRight").scrollTop = document.getElementById("fundLeft").scrollTop;
    };

    document.getElementById("fundRight").onscroll = function () {
      document.getElementById("fundLeft").scrollTop = document.getElementById("fundRight").scrollTop;
    };*/
  }

  ionViewDidEnter() {
    // document.getElementById("headerDivider").style.transition = null;
    this.segmentChanged();

    //初始化持仓分析显示样式
    document.getElementById("showByDetail").style.display = "flex";
    document.getElementById("showByMaturityDate").style.display = "none";
  };

  segmentChanged() {

    //试算结果
    if (this.resultType != "TrialCalculationResult") {
      document.getElementById("TrialCalculationResult").style.display = "none";
    } else {
      document.getElementById("TrialCalculationResult").style.display = "block";
      if (document.getElementById("SegmentScroll")) {
        document.getElementById("SegmentScroll").getElementsByClassName("scroll-content")[0].scrollLeft = 0;
      }
    }

    // 分级基金试算结果
    if (this.resultType != "StructuredFundTrialCalculationResult") {
      document.getElementById("StructuredFundTrialCalculationResult").style.display = "none";
    } else {
      document.getElementById("StructuredFundTrialCalculationResult").style.display = "block";
      if (document.getElementById("SegmentScroll")) {
        document.getElementById("SegmentScroll").getElementsByClassName("scroll-content")[0].scrollLeft = 600;
      }
    }

    // 持仓分析
    if (this.resultType != "PositionTrialCalculationResult") {
      document.getElementById("PositionTrialCalculationResult").style.display = "none";
    } else {
      document.getElementById("PositionTrialCalculationResult").style.display = "block";
      if (document.getElementById("SegmentScroll")) {
        document.getElementById("SegmentScroll").getElementsByClassName("scroll-content")[0].scrollLeft = 600;
      }
    }

    // 模拟情景
    if (this.resultType != "SimulatedSceneList") {
      document.getElementById("SimulatedSceneList").style.display = "none";
    } else {
      document.getElementById("SimulatedSceneList").style.display = "block";
      if (document.getElementById("SegmentScroll")) {
        document.getElementById("SegmentScroll").getElementsByClassName("scroll-content")[0].scrollLeft = 0;
      }
    }

  }

  initListData() {
    this.listData = {
      noDatas: true,
      fundName: "",
      structuredFund: [],
      column: [],
      StructuredFundColumn: [],
      PositionColumn: [],
      MaturityColumn: [],
      SimulatedSceneColumn: [],
      positionList: [],
      maturityDateList: [],
      trialCalculationResult: [],
      structuredFundTrialCalculationResult: [],
      positionTrialCalculationResult: [],
      simulatedScenePlan: []
    }
  }

  initQueryCondition() {
    this.queryCondition = {
      fund_name: "",
      fund_code: "",
      l_begin_date: "",
      l_his_days: 1,
      l_fut_days: 3,
      simulatedScene: "0"
    };

    this.queryCondition.l_begin_date = this.common.getNowFormatDate();
    if (!this.config.isProduct) {
      this.queryCondition.l_begin_date = "2015-05-05";
    }

    this.storage.get("userInfo").then(user => {
      this.userInfo = user;
      this.storage.get("ipm_coin_query_condition_" + this.userInfo.loginid).then(queryCondition => {
        if (queryCondition) {
          this.queryCondition.fund_name = queryCondition.fund_name;
          this.queryCondition.fund_code = queryCondition.fund_code;
          this.queryCondition.l_his_days = queryCondition.l_his_days;
          this.queryCondition.l_fut_days = queryCondition.l_fut_days;
          this.queryCondition.simulatedScene = queryCondition.simulatedScene;
        }
      });
    });
  }

  initFilterPositionCondition() {
    this.filterPositionCondition = {
      l_begin_date: "",
      isSearchByDate: false,
      showByMaturityDate: false,
      startDate: "",
      endDate: ""
    }
  }

  initSortCondition() {
    this.sortCondition = {
      "TrialCalculationResult": {
        sortField: "",
        sortType: ""
      },
      "StructuredFundTrialCalculationResult": {
        sortField: "",
        sortType: ""
      },
      "PositionTrialCalculationResult": {
        sortField: "",
        sortType: ""
      }
    }
  }

  /**
   * 初始化模拟情景下拉选择
   */
  initSimulatedSceneList() {
    this.simulatedSceneList = [];
    this.coinService.getSimulatedScene().subscribe(simulatedScene => {
      this.simulatedSceneList.push({
        "l_plan_no": "0",
        "vc_plan_name": "无情景",
        "vc_user": "",
        "l_create_date": ""
      });
      if (simulatedScene) {
        this.simulatedSceneList = _.concat(this.simulatedSceneList, simulatedScene);
      }
      let temp = _.find(this.simulatedSceneList, {l_plan_no: this.queryCondition.simulatedScene});
      if (!temp) {
        this.queryCondition.simulatedScene = 0;
      }
      console.log("simulatedSceneList", this.simulatedSceneList);
    });
  }

  selectFund() {
    let profileModal = this.modalCtrl.create(IpmCirculateModal, {
      selectedFund: this.selectedFund,
      fundType: "4",
      selectOne: true
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        this.selectedFund = [];
        this.selectedFund.push(data);
        this.queryCondition.fund_code = _.toString(_.map(this.selectedFund, "vc_fund_code"));
        this.queryCondition.fund_name = _.toString(_.map(this.selectedFund, "vc_fund_name"));
      }
    });
    profileModal.present();
  }

  setShowQueryCondition() {
    this.showQueryCondition = !this.showQueryCondition;
    this.content.scrollToTop();
  }

  setShowQueryParams() {
    this.showQueryParams = !this.showQueryParams;
  }

  search() {
    this.isLoadMore = true;
    if (this.queryCondition.fund_code === "") {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: "请选择基金",
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });
      alert.present();
      return;
    }

    if (parseFloat(this.queryCondition.l_fut_days) <= 0) {
      this.common.alertMessage("试算天数不能为零");
      return false;
    }

    this.initSortCondition();
    this.initListData();
    this.setShowQueryCondition();
    this.filterPositionCondition.l_begin_date = this.queryCondition.l_begin_date;
    this.filterPositionCondition.startDate = this.queryCondition.l_begin_date;
    this.storage.set("ipm_coin_query_condition_" + this.userInfo.loginid, this.queryCondition);
    this.loadDatas();
  }

  setShowListItem(item) {
    item.expanded = !item.expanded;
  }

  setShowMoreField(item) {
    item.showMoreField = !item.showMoreField;
  }

  expandPosition(item) {
    item.expand = !item.expand;
    this.initDataGrid();
  }

  /**
   * 按字段排序
   * @param fieldName
   */
  sortByField(fieldName) {
    switch (this.resultType) {
      case "StructuredFundTrialCalculationResult":
        this.sortCondition[this.resultType].sortField = fieldName;
        switch (this.sortCondition[this.resultType].sortType) {
          case "up":
            this.sortCondition[this.resultType].sortType = "down";
            this.listData.structuredFundTrialCalculationResult =
              _.sortBy(this.listData.structuredFundTrialCalculationResult, fieldName);
            this.listData.structuredFundTrialCalculationResult =
              _.reverse(this.listData.structuredFundTrialCalculationResult);
            break;
          case "down":
            this.sortCondition[this.resultType].sortType = "up";
            this.listData.structuredFundTrialCalculationResult =
              _.sortBy(this.listData.structuredFundTrialCalculationResult, fieldName);
            break;
          default:
            this.sortCondition[this.resultType].sortType = "up";
            this.listData.structuredFundTrialCalculationResult =
              _.sortBy(this.listData.structuredFundTrialCalculationResult, fieldName);
            break;
        }
        break;
    }
    console.log(this.sortCondition);
  }

  /**
   * [loadListData 加载列表数据]
   */
  loadDatas() {
    /* this.coinService.getCoinTrialCalculationResult(this.queryCondition).subscribe(data => {
      console.log(data);
      if (data) {
        this.listData.fundName = data.fundName;
        this.listData.structuredFund = data.structuredFund;
        this.listData.trialCalculationResult = data.trialCalculationResult;
        this.listData.structuredFundTrialCalculationResult = data.structuredFundTrialCalculationResult;
        this.listData.positionTrialCalculationResult = data.positionTrialCalculationResult;
        this.listData.simulatedScenePlan = data.simulatedScenePlan;

        this.listData.noDatas = false;
        this.listData.column = _.filter(this.fieldColumnModel.entity.TrialCalculationResult.fieldColumns,
          {isShow: true});
        this.listData.StructuredFundColumn = _.filter(this.fieldColumnModel.entity.StructuredFundTrialCalculationResult.fieldColumns,
          {isShow: true});
        this.listData.MaturityColumn = this.fieldColumnModel.entity.maturityDateColumn.fieldColumns;
        this.listData.SimulatedSceneColumn = _.filter(this.fieldColumnModel.entity.SimulatedSceneList.fieldColumns,
          {isShow: true});

        this.formatData();

        // document.getElementById("GridTitle").style.width = 200 * this.listData.column.length + "px";
        // document.getElementById("gridRight").style.height = 4.4 * (this.listData.trialCalculationResult.length + 1) + "rem";
        this.initDataGrid();
        console.log(this.listData);
      } else {
        this.isLoadMore = false;
      }

    }); */
    let loading = this.loadingCtrl.create({
      content: "加载中,请稍候...",
    });
    loading.present();

    this.coinService.getCoinTrialResult(this.queryCondition).subscribe( data => {
      if(data){
        this.coinService.getCoinCaculateDatas(this.queryCondition).subscribe( data => {
          console.log('coin trial data') 
          loading.dismiss();
          this.processData(data, "cointrial");
          this.listData.noDatas = false;       
        });

        this.coinService.getStructuredFundTrialDatas(this.queryCondition).subscribe( data => {
          console.log('StructuredFundTrialDatas')
           
          this.processData(data, "structuredFund");
        })

        this.coinService.getPositionTrialDatas(this.queryCondition).subscribe( data => {
          console.log('PositionTrialDatas')
          this.processData(data, "positionTrial");
          this.requestLoading.positionTrial = true;
        })

        this.coinService.getSimulatedSceneDatas(this.queryCondition).subscribe( data => {
          console.log('SimulatedSceneDatas')
          this.processData(data, "simulatedScene");
          this.requestLoading.simulatedScene = true;
        })
      } else{
        loading.dismiss();
        this.isLoadMore = false;
      }
      
    })
  }

  processData(data, type){
    this.listData.fundName = data.fundName;
    switch(type) {
      case "cointrial":
        this.listData.trialCalculationResult = data.trialCalculationResult;
        this.listData.column = _.filter(this.fieldColumnModel.entity.TrialCalculationResult.fieldColumns,
          {isShow: true});
        break;
      case "structuredFund":
        this.listData.structuredFund = data.structuredFund;
        this.listData.structuredFundTrialCalculationResult = data.structuredFundTrialCalculationResult;
        this.listData.StructuredFundColumn = _.filter(this.fieldColumnModel.entity.StructuredFundTrialCalculationResult.fieldColumns,
          {isShow: true});
        break;
      case "positionTrial":
        this.listData.positionTrialCalculationResult = data.positionTrialCalculationResult;
        this.listData.MaturityColumn = this.fieldColumnModel.entity.maturityDateColumn.fieldColumns;
        break;
      case "simulatedScene":
        this.listData.simulatedScenePlan = data.simulatedScenePlan;
        this.listData.SimulatedSceneColumn = _.filter(this.fieldColumnModel.entity.SimulatedSceneList.fieldColumns,
          {isShow: true});
        break;
    } 

    this.formatData();
    this.initDataGrid();
    console.log(this.listData);
  }

  formatData() {
    console.log("11111", this.listData.trialCalculationResult.length);
    _.forEach(this.listData.trialCalculationResult, trialCalculationResult => {
      trialCalculationResult["showMoreField"] = false;
      trialCalculationResult["l_date"] = _.replace(trialCalculationResult["l_date"], /-/g, "");
      trialCalculationResult["l_date"] = trialCalculationResult["l_date"].substr(0, 4) + "-" +
        trialCalculationResult["l_date"].substr(4, 2) + "-" +
        trialCalculationResult["l_date"].substr(6, 2);
      /*let keys = _.keys(trialCalculationResult);
      _.forEach(keys, key => {
        let field = _.find(this.fieldColumnModel["entity"]["TrialCalculationResult"]["fieldColumns"],
          {fieldName: key, isShow: true});
        if (field) {
          if (field["isNumber"]) {
            if (trialCalculationResult[key] && trialCalculationResult[key] != "-") {
              trialCalculationResult[key] = _.replace(trialCalculationResult[key], /,/g, "");
              trialCalculationResult[key] = this.common.formatNumberToAccountancy2(trialCalculationResult[key], 4);
            } else {
              trialCalculationResult[key] = "-";
            }
          }
        }
      });*/
    });

    /**
     * 处理分级基金试算结果的数据
     */
    if (this.listData.structuredFund && this.listData.structuredFund.length > 0) {
      _.forEach(this.listData.structuredFundTrialCalculationResult, structuredFundTrialCalculationResult => {
        structuredFundTrialCalculationResult["l_date"] = _.replace(structuredFundTrialCalculationResult["l_date"], /-/g, "");
        structuredFundTrialCalculationResult["l_date"] = structuredFundTrialCalculationResult["l_date"].substr(0, 4) + "-" +
          structuredFundTrialCalculationResult["l_date"].substr(4, 2) + "-" +
          structuredFundTrialCalculationResult["l_date"].substr(6, 2);
        /*let keys = _.keys(structuredFundTrialCalculationResult);
        _.forEach(keys, key => {
          let field = _.find(this.fieldColumnModel["entity"]["StructuredFundTrialCalculationResult"]["fieldColumns"],
            {fieldName: key, isShow: true});
          if (field) {
            if (field["isNumber"]) {
              if (structuredFundTrialCalculationResult[key] && structuredFundTrialCalculationResult[key] != "-") {
                structuredFundTrialCalculationResult[key] = _.replace(structuredFundTrialCalculationResult[key], /,/g, "");
                structuredFundTrialCalculationResult[key] =
                  this.common.formatNumberToAccountancy2(structuredFundTrialCalculationResult[key], 4);
              } else {
                structuredFundTrialCalculationResult[key] = "-";
              }
            }
          }
        });*/
      });
    }


    let resultList = _.filter(this.listData.positionTrialCalculationResult, result => {
      let l_date = _.replace(this.filterPositionCondition.l_begin_date, /-/g, "");
      return result["l_date"] === l_date && result["l_maturity_date"].length === 8;
    });
    let l_maturity_dates = _.map(resultList, "l_maturity_date");

    let max_l_maturity_date = _.toString(_.max(l_maturity_dates));
    if (max_l_maturity_date) {
      this.filterPositionCondition.endDate = _.replace(this.filterPositionCondition.endDate, /-/g, "");
      this.filterPositionCondition.endDate = max_l_maturity_date.substr(0, 4) + "-" +
        max_l_maturity_date.substr(4, 2) + "-" + max_l_maturity_date.substr(6, 2);
    }
    console.log("filterPositionCondition", this.filterPositionCondition);
    this.dealPositionData();


    /**
     * 处理模拟情景的方案数据
     */
    _.forEach(this.listData.simulatedScenePlan, simulatedScenePlan => {
      simulatedScenePlan["l_date"] = _.replace(simulatedScenePlan["l_date"], /-/g, "");
      simulatedScenePlan["l_date"] = simulatedScenePlan["l_date"].substr(0, 4) + "-" +
        simulatedScenePlan["l_date"].substr(4, 2) + "-" +
        simulatedScenePlan["l_date"].substr(6, 2);
      /*let keys = _.keys(simulatedScenePlan);
      _.forEach(keys, key => {
        let field = _.find(this.fieldColumnModel["entity"]["SimulatedSceneList"]["fieldColumns"],
          {fieldName: key, isShow: true});
        if (field) {
          if (field["isNumber"]) {
            if (simulatedScenePlan[key] && simulatedScenePlan[key] != "-") {
              simulatedScenePlan[key] = _.replace(simulatedScenePlan[key], /,/g, "");
              simulatedScenePlan[key] = this.common.formatNumberToAccountancy2(simulatedScenePlan[key], 4);
              if (key === "en_yield") {
                console.log("simulatedScenePlan[key]", simulatedScenePlan[key]);
              }
            } else {
              simulatedScenePlan[key] = "-";
            }
          }
        }
      });*/
    });


    console.log("formatNumberToAccountancy2", this.common.formatNumberToAccountancy2("0.1", 4));
  }

  /**
   * 处理持仓分析的数据
   */
  dealPositionData() {
    this.listData.positionList = [];
    this.listData.positionList = _.concat(this.listData.positionList, this.fieldColumnModel.entity.positionList);
    _.forEach(this.listData.positionList, position => {
      position.expand = false;
      position.data = [];
      _.forEach(this.listData.positionTrialCalculationResult, result => {
        let l_date = _.replace(this.filterPositionCondition.l_begin_date, /-/g, "");
        if (result["vc_parentid"] === position.type && result["l_date"] === l_date) {
          let temp = _.clone(result);
          if (this.filterPositionCondition.isSearchByDate) {
            let startDate = _.replace(this.filterPositionCondition.startDate, /-/g, "");
            let endDate = _.replace(this.filterPositionCondition.endDate, /-/g, "");
            if (result["l_maturity_date"] >= startDate && result["l_maturity_date"] <= endDate) {
              position.data.push(temp);
            }
          } else {
            position.data.push(temp);
          }
        }
      });

      this.countFieldData(position);

      if (position.type != "p6") {
        let mrsylv = 0;
        let mrsylv_en_td_amount = 0;
        _.forEach(position.data, (data, i:number) => {

          if (data["en_hold_yield"] != "-" && data["en_hold_yield"] != "") {
            mrsylv_en_td_amount += parseFloat(_.replace(data["en_hold_yield"], /,/g, ""))
              * parseFloat(_.replace(data["en_td_amount"], /,/g, ""));
          }
        });
        mrsylv = parseFloat((parseFloat(mrsylv_en_td_amount.toFixed(2))
          / parseFloat(parseFloat(_.replace(position.field["en_td_cost"], /,/g, "")).toFixed(2))).toFixed(2));
        position.field["en_hold_yield"] = mrsylv;
        if (position.type === "p3" || position.type === "p5") {
          //清空回购汇总的剩余天数贡献度[en_td_rest_day_degree]字段
          position.field["en_td_rest_day_degree"] = "";
        }
      } else {
        position.field["en_hold_yield"] = "-";
        position.field["l_td_rest_day"] = "-";
        position.field["en_td_quantity"] = "-";
      }

      /*_.forEach(position.data, data => {
        let keys = _.keys(data);
        _.forEach(keys, key => {
          let field = _.find(this.fieldColumnModel["entity"]["PositionTrialCalculationResult"]["fieldColumns"],
            {fieldName: key, isShow: true});
          if (field) {
            if (field["isNumber"]) {

              if (["en_td_float_ratio", "en_yield", "en_td_rest_day_degree"].indexOf(key) > -1) {
                if (data[key]) {
                  data[key] = _.toString(parseFloat(data[key]).toFixed(4));
                }
              } else {
                if (data[key]) {
                  if (field["nullShowLine"] && data[key] && data[key] === "0") {
                    if (key != "en_hold_yield") {
                      data[key] = "";
                    }
                  } else {
                    data[key] = _.toString(parseFloat(data[key]).toFixed(2));
                  }
                }
              }

              if (!field["nullShowLine"]) {
                if ((position.type === "p3" || position.type === "p5") && key === "en_td_rest_day_degree") {
                  //回购的剩余天数贡献度[en_td_rest_day_degree]字段不做处理
                } else {
                  data[key] = _.replace(data[key], /,/g, "");
                  // data[key] = data[key] ? data[key] : "0";
                  if (data[key]) {
                    data[key] = this.common.formatNumberToAccountancy2(data[key], 4);
                  } else {
                    data[key] = "-";
                  }
                }
              } else {
                if (data[key] && data[key] != "-") {
                  data[key] = _.replace(data[key], /,/g, "");
                  data[key] = this.common.formatNumberToAccountancy2(data[key], 4);
                } else {
                  data[key] = "-";
                }
              }
            } else {
              if (field["nullShowLine"]) {
                if (!data[key] || data[key] === "") {
                  data[key] = "-"
                }
              }
            }
          }
        });
      });*/

      position.field["en_net"] = "-";
      position.field["en_td_price"] = "-";
      position.field["en_coupon_rate"] = "-";
      position.field["en_yield"] = "-";
    });

  }

  dealMaturityDateList() {
    this.listData.maturityDateList = [];
    let temp_ResultList = _.filter(this.listData.positionTrialCalculationResult, result => {
      let filterResult = false;
      if (result["l_maturity_date"] != "" && result["l_maturity_date"].length === 8) {
        if (result["l_maturity_date"] >= _.replace(this.filterPositionCondition.startDate, /-/g, "")
          && result["l_maturity_date"] <= _.replace(this.filterPositionCondition.endDate, /-/g, "")) {
          filterResult = true;
        }
      }
      return filterResult;
    });
    console.log("temp_ResultList", temp_ResultList);

    let l_maturity_dateList = _.uniq(_.map(temp_ResultList, "l_maturity_date"));
    console.log("l_maturity_dateList", l_maturity_dateList);
    _.forEach(l_maturity_dateList, (date:string) => {
      let temp_date = date.substr(0, 4) + "-" +
        date.substr(4, 2) + "-" + date.substr(6, 2);
      let maturityDate = {
        date: temp_date,
        field: {},
        expand: false,
        position: [],
        data: [],
        total: 0
      };
      let maturityPosList = _.cloneWith(this.fieldColumnModel.entity.positionList);
      _.forEach(maturityPosList, pos => {
        let temp_pos = _.clone(pos);
        temp_pos["expand"] = false;
        temp_pos.data = [];
        _.forEach(this.listData.positionTrialCalculationResult, result => {
          if (result["vc_parentid"] === temp_pos.type
            && result["l_maturity_date"] === date
            && result["l_date"] === _.replace(this.filterPositionCondition.l_begin_date, /-/g, "")) {
            if ((!result["en_td_quantity"] || result["en_td_quantity"] === "0")
              && (!result["en_td_amount"] || result["en_td_amount"] === "0")
              && (!result["en_td_cost"] || result["en_td_cost"] === "0")
              && (!result["en_net_degree"] || result["en_net_degree"] === "0")) {

            } else {
              let temp = _.clone(result);
              temp_pos.data.push(temp);
            }
          }
        });
        if (temp_pos.data.length > 0) {
          temp_pos.field = {};
          this.countFieldData(temp_pos);
          maturityDate.total += temp_pos.data.length;
          maturityDate.data.push(temp_pos.field);
          maturityDate.position.push(temp_pos);
        }
      });
      this.countFieldData(maturityDate);
      this.listData.maturityDateList.push(maturityDate);
    });
    this.listData.maturityDateList = _.sortBy(this.listData.maturityDateList, maturity => {
      return maturity["date"];
    });
    console.log("listData.maturityDateList", this.listData.maturityDateList);
  }

  /**
   * 计算字段总和
   * @param position
   */
  countFieldData(position) {
    let keys = this.fieldColumnModel.entity.PositionTrialCalculationResult.fieldColumns;
    _.forEach(keys, key => {
      let num = 0;
      // console.log("key", key);
      // console.log("position.data", position.data);
      if (key.isNumber) {
        let valueList = _.map(position.data, key.fieldName);
        // console.log("valueList", valueList);
        _.forEach(valueList, (value: string) => {
          if (value != "" && value != "-") {
            value = _.replace(value, /,/g, "");
            num += parseFloat(value);
          }
        });

        let temp_valueList = _.filter(position.data, data => {
          return data[key.fieldName] != "" && data[key.fieldName] != "-";
        });
        if (temp_valueList.length > 0) {
          position.field[key.fieldName] = _.toString(num);
          /*if (["en_td_float_ratio", "en_yield", "en_td_rest_day_degree"].indexOf(key.fieldName) > -1) {
            position.field[key.fieldName] = this.common.formatNumberToAccountancy2(num, 4);
          } else {
            position.field[key.fieldName] = this.common.formatNumberToAccountancy2(num, 2);
          }*/
        } else {
          position.field[key.fieldName] = "-";
        }
      } else {
        if (key.nullShowLine) {
          if (!position.field[key.fieldName] || position.field[key.fieldName] === "") {
            position.field[key.fieldName] = "-";
          }
        }
      }

      //获取子项中为0的个数
      /*let zeroItems = _.filter(position.data, data => {
        return _.toString(parseFloat(data[key.fieldName]).toFixed(4)) === "0.0000";
      });
      if (zeroItems.length > 0 && _.toString(parseFloat(position.field[key.fieldName]).toFixed(4)) === "0.0000") {
        //子项中不存在为0的记录，若总数为0，则显示-
        if (key.nullShowLine) {
          position.field[key.fieldName] = "-";
        }
      }*/
    });
  }

  initDataGrid() {
    this.listData.column = _.filter(this.fieldColumnModel.entity.TrialCalculationResult.fieldColumns,
      {isShow: true});
    this.listData.StructuredFundColumn = _.filter(this.fieldColumnModel.entity.StructuredFundTrialCalculationResult.fieldColumns,
      {isShow: true});
    this.listData.PositionColumn = _.filter(this.fieldColumnModel.entity.PositionTrialCalculationResult.fieldColumns,
      {isShow: true});
    this.listData.SimulatedSceneColumn = _.filter(this.fieldColumnModel.entity.SimulatedSceneList.fieldColumns,
      {isShow: true});

    document.getElementById("GridTitle_TrialCalculationResult").style.width = 200 *
      this.listData.column.length + "px";
    document.getElementById("gridRight_TrialCalculationResult").style.height = 4.4 *
      (this.listData.trialCalculationResult.length + 1) + "rem";

    //根据试算日期以及是否显示全部日期过滤分级基金数据
    let temp_fields = _.filter(this.listData.structuredFundTrialCalculationResult, field => {
      return field["l_date"] === this.queryCondition.l_begin_date || this.structuredFund_ShowAllDate;
    });
    document.getElementById("GridTitle_StructuredFundTrialCalculationResult").style.width = 200 *
      this.listData.StructuredFundColumn.length + "px";
    document.getElementById("gridRight_StructuredFundTrialCalculationResult").style.height = 4.4 *
      (temp_fields.length + 2) + "rem";

    //设置持仓分析表格宽高
    document.getElementById("GridTitle_PositionTrialCalculationResult").style.width = 200 *
      this.listData.PositionColumn.length + "px";
    let temp_positionList = _.filter(this.listData.positionList, pos => {
      return pos["data"].length > 0;
    });
    let row = temp_positionList.length + 2;
    _.forEach(temp_positionList, pos => {
      if (pos["expand"]) {
        row += pos["data"].length;
      }
    });
    document.getElementById("gridRight_PositionTrialCalculationResult").style.height = 4.4 * row + "rem";
    //设置持仓分析按到期日显示时的表格宽高
    document.getElementById("GridTitle_MaturityDateResult").style.width = 200 *
      this.listData.MaturityColumn.length + "px";
    let maturity_row = this.listData.maturityDateList.length + 2;
    _.forEach(this.listData.maturityDateList, maturity => {
      if (maturity.expand) {
        maturity_row += maturity.position.length;
        _.forEach(maturity.position, pos => {
          if (pos.expand) {
            maturity_row += pos.data.length;
          }
        });
      }
    });
    document.getElementById("gridRight_MaturityDateResult").style.height = 4.4 * maturity_row + "rem";

    document.getElementById("GridTitle_SimulatedSceneList").style.width = 200 *
        this.listData.SimulatedSceneColumn.length + "px";
    document.getElementById("gridRight_SimulatedSceneList").style.height = 4.4 *
      (this.listData.simulatedScenePlan.length + 2) + "rem";
  }

  showAllDateChange() {
    this.structuredFund_ShowAllDate = !this.structuredFund_ShowAllDate;
    this.initDataGrid();
  }

  showByMaturityDateChange() {
    this.filterPositionCondition.showByMaturityDate  = !this.filterPositionCondition.showByMaturityDate;
    if (this.filterPositionCondition.showByMaturityDate) {
      document.getElementById("showByMaturityDate").style.display = "flex";
      document.getElementById("showByDetail").style.display = "none";
      this.dealMaturityDateList();
    } else {
      document.getElementById("showByDetail").style.display = "flex";
      document.getElementById("showByMaturityDate").style.display = "none";
      this.dealPositionData();
    }
    this.initDataGrid();
  }

  goPos() {
    let offsetHeight = document.getElementById("inputEnValue").offsetHeight;
    if (this.plt.is("android")) {
      console.log(offsetHeight);
      this.content.scrollTo(0, offsetHeight * 5);
    }
  }

  newDate(date) {
    return new Date(date);
  }

  moreOp() {
    let buttons = [];
    if (this.listData.noDatas) {
      buttons.push({
        text: "新建模拟情景",
        handler: () => {
          this.addSimulatedScene();
        }
      });
      buttons.push({
        text: "批量删除模拟情景",
        handler: () => {
          this.batchDeleteSimulatedScene();
        }
      });
      if (this.queryCondition.simulatedScene != "0") {
        buttons.push({
          text: "删除模拟情景",
          role: "destructive",
          handler: () => {
            this.deleteSimulatedScene();
          }
        });
        buttons.push({
          text: "添加模拟方案",
          handler: () => {
            this.saveSimulatedScene();
          }
        });
      }
    } else {
      switch (this.resultType) {
        case "TrialCalculationResult":
          buttons.push({
            text: "自定义列",
            handler: () => {
              this.openColumnModal("TrialCalculationResult");
            }
          });
          break;
        case "StructuredFundTrialCalculationResult":
          buttons.push({
            text: "自定义列",
            handler: () => {
              this.openColumnModal("StructuredFundTrialCalculationResult");
            }
          });
          if (this.structuredFund_ShowAllDate) {
            buttons.push({
              text: "取消显示全部日期",
              handler: () => {
                this.showAllDateChange();
              }
            });
          } else {
            buttons.push({
              text: "显示全部日期",
              handler: () => {
                this.showAllDateChange();
              }
            });
          }
          break;
        case "PositionTrialCalculationResult":
          if (this.filterPositionCondition.showByMaturityDate) {
            buttons.push({
              text: "数据过滤",
              handler: () => {
                this.openFilterPositionModal();
              }
            });
            buttons.push({
              text: "取消按到期日显示",
              handler: () => {
                this.showByMaturityDateChange();
              }
            });
          } else {
            buttons.push({
              text: "自定义列",
              handler: () => {
                this.openColumnModal("PositionTrialCalculationResult");
              }
            });
            buttons.push({
              text: "数据过滤",
              handler: () => {
                this.openFilterPositionModal();
              }
            });
            buttons.push({
              text: "按到期日显示",
              handler: () => {
                this.showByMaturityDateChange();
              }
            });
          }
          break;
        case "SimulatedSceneList":
          buttons.push({
            text: "自定义列",
            handler: () => {
              this.openColumnModal("SimulatedSceneList");
            }
          });
          buttons.push({
            text: "新建模拟情景",
            handler: () => {
              this.addSimulatedScene();
            }
          });
          buttons.push({
            text: "批量删除模拟情景",
            handler: () => {
              this.batchDeleteSimulatedScene();
            }
          });
          if (this.queryCondition.simulatedScene != "0") {
            buttons.push({
              text: "删除模拟情景",
              role: "destructive",
              handler: () => {
                this.deleteSimulatedScene();
              }
            });
            buttons.push({
              text: "添加模拟方案",
              handler: () => {
                this.saveSimulatedScene();
              }
            });
          }
          break;
      }
    }
    let firstItem = [];
    /*if (!this.listData.noDatas) {
      firstItem.push({
        text: "全屏显示",
        handler: () => {
          this.setShowByLandscape(1);
        }
      });
    }*/
    buttons.push({
      text: "取消",
      role: 'cancel',
      handler: () => {
      }
    });
    let actionSheet = this.actionSheetCtrl.create({
      title: "",
      buttons: _.concat(firstItem, buttons)
    });

    actionSheet.present();
  }

  openColumnModal(type) {
    let profileModal = this.modalCtrl.create(IpmColumnModal, {
      resultType: type
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        let CustomFieldColumns = {};
        CustomFieldColumns[type] = data;
        this.fieldColumnModel["entity"][type]["fieldColumns"] = data;
        this.storage.set("CustomFieldColumns", CustomFieldColumns);
        this.formatData();
        this.initDataGrid();
      }
    });
    profileModal.present();
  }

  openFilterPositionModal() {
    let profileModal = this.modalCtrl.create(IpmCoinFilterModal, {
      filterCondition: this.filterPositionCondition
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        this.filterPositionCondition = data;
        if (this.filterPositionCondition.showByMaturityDate) {
          this.dealMaturityDateList();
        } else {
          this.dealPositionData();
        }
      }
    });
    profileModal.present();
  }

  /**
   * 模拟情景模块的更多操作
   */
  simulatedSceneMoreOps() {

    let buttons = [{
      text: "新建模拟情景",
      handler: () => {
        this.addSimulatedScene();
      }
    }];
    if (this.queryCondition.simulatedScene != "0") {
      let temp_button = {
        text: "删除模拟情景",
        role: "destructive",
        handler: () => {
          this.deleteSimulatedScene();
        }
      };
      buttons.push(temp_button);
    }

    buttons = _.concat(buttons, [{
      text: "批量删除模拟情景",
      handler: () => {
        this.batchDeleteSimulatedScene();
      }
    }, {
      text: "添加模拟方案",
      handler: () => {
        this.saveSimulatedScene();
      }
    }, {
      text: "取消",
      role: 'cancel',
      handler: () => {

      }
    }]);

    let actionSheet = this.actionSheetCtrl.create({
      title: "",
      buttons: buttons
    });

    actionSheet.present();
  }

  addSimulatedScene() {
    let alert = this.alertCtrl.create({
      title: '新建模拟情景',
      inputs: [
        {
          name: 'simulateScene',
          placeholder: '请输入模拟情景名称'
        }
      ],
      cssClass: "alert-center",
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: data => {

          }
        },
        {
          text: '保存',
          handler: data => {

            if (data["simulateScene"] === "") {
              this.common.alertMessage("请输入模拟情景名称");
            } else {

              let temp_scene = _.find(this.simulatedSceneList, {"vc_plan_name": data["simulateScene"]});

              if (temp_scene) {
                this.common.alertMessage("模拟情景已存在");
                return false;
              } else {
                this.storage.get("userInfo").then(user => {
                  this.coinService.saveSimulatedScene(user, data["simulateScene"]).subscribe(saveResult => {
                    console.log("saveSimulatedScene", saveResult);
                    if (saveResult) {
                      return false;
                    }
                    this.common.alertMessage("模拟情景保存成功");
                    this.initSimulatedSceneList();
                  });
                });
              }
            }
          }
        }
      ]
    });
    alert.present();
    document.getElementsByTagName("ion-alert")[0].className =
      _.replace(document.getElementsByTagName("ion-alert")[0].className, "alert-top", "");
  }

  /**
   * 删除模拟情景
   */
  deleteSimulatedScene() {
    let scene = _.find(this.simulatedSceneList, {l_plan_no: this.queryCondition.simulatedScene});
    let alert = this.alertCtrl.create({
      title: "提示",
      message: "确定要删除\"(模拟情景:" + scene["vc_plan_name"] + ")\",该模拟情景下的试算方案也将全部删除？",
      buttons: [{
          text: '取消',
          role: 'cancel',
          handler: () => {

          }
        }, {
          text: "确定",
          handler: () => {
            this.coinService.deleteSimulatedScene(scene["l_plan_no"]).subscribe(deleteResult => {
              console.log("deleteSimulatedScene", deleteResult);
              if (deleteResult && deleteResult[0] && deleteResult[0]["l_err_code"] === "0") {
                this.common.alertMessage("模拟情景已删除");
                this.initSimulatedSceneList();
              } else {
                this.common.alertMessage("删除模拟情景出错");
              }
            });
          }
        }]
    });
    alert.present();
  }

  /**
   * 批量删除模拟情景
   */
  batchDeleteSimulatedScene() {
    let profileModal = this.modalCtrl.create(IpmCoinDeleteModal, {
      dataList: this.simulatedSceneList
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        this.initSimulatedSceneList();
      }
    });
    profileModal.present();
  }

  simulatedScenePlanOps(item) {
    if (this.showByLandscape) {
      return false;
    }

    let buttons = [{
      text: "修改方案",
      handler: () => {
        this.editSimulatedScene(item);
      }
    }, {
      text: "删除方案",
      role: "destructive",
      handler: () => {
        this.deleteSimulatedScenePlan(item);
      }
    }, {
      text: "取消",
      role: 'cancel',
      handler: () => {

      }
    }];

    let actionSheet = this.actionSheetCtrl.create({
      title: "",
      buttons: buttons
    });

    actionSheet.present();
  }

  deleteSimulatedScenePlan(item) {

    let alert = this.alertCtrl.create({
      title: "提示",
      message: "确定要删除\"(流水号为:" + item["l_serial_no"] + "的试算方案)\"？",
      buttons: [{
        text: '取消',
        role: 'cancel',
        handler: () => {

        }
      }, {
        text: "确定",
        handler: () => {
          this.coinService.deleteSimulatedScenePlan(item["l_serial_no"]).subscribe(deleteResult => {
            console.log("deleteSimulatedScene", deleteResult);
            this.common.alertMessage("试算方案已删除");
            _.remove(this.listData.simulatedScenePlan, plan => {
              return plan["l_serial_no"] === item["l_serial_no"];
            });
            /*if (deleteResult && deleteResult[0] && deleteResult[0]["l_err_code"] === "0") {
              this.common.alertMessage("试算方案已删除");
              _.remove(this.listData.simulatedScenePlan, plan => {
                return plan["l_serial_no"] === item["l_serial_no"];
              });
            } else {
              this.common.alertMessage("删除试算方案出错");
            }*/
          });
        }
      }]
    });
    alert.present();
  }

  saveSimulatedScene() {
    if (this.queryCondition.fund_code === "") {
      this.common.alertMessage("请先选择基金");
      return false;
    }
    let profileModal = this.modalCtrl.create(IpmCoinSaveSceneModal, {
      isEdit: false,
      fundCode: this.queryCondition.fund_code,
      planNo: this.queryCondition.simulatedScene
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        if (data["isSuccess"] && !this.listData.noDatas) {
          this.loadDatas();
        }
      }
    });
    profileModal.present();
  }

  editSimulatedScene(item) {
    console.log("editSimulatedScene.item", item);
    let profileModal = this.modalCtrl.create(IpmCoinSaveSceneModal, {
      isEdit: true,
      fundCode: this.queryCondition.fund_code,
      planNo: this.queryCondition.simulatedScene,
      oldData: item
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        if (data["isSuccess"]) {
          this.loadDatas();
        }
      }
    });
    profileModal.present();
  }

  selectStockNo() {

  }

  addToSimulateScene(position, addData) {
    if (this.showByLandscape) {
      return false;
    }

    if (position.type != "p1" && position.type != "p2") {
      return false;
    } else {
      addData.selectItemColor = "selectedItem";
      let inputs = [];
      _.forEach(this.simulatedSceneList, scene => {
        if (scene.l_plan_no != "0") {
          let temp = {
            name: "simulateScene",
            label: scene.vc_plan_name,
            value: scene.l_plan_no,
            checked: false,
            type: "radio"
          };
          inputs.push(temp);
        }
      });
      let buttons = [{
        text: "添加到模拟情景",
        handler: () => {
          let alert = this.alertCtrl.create({
            title: '',
            inputs: inputs,
            buttons: [
              {
                text: '取消',
                role: 'cancel',
                handler: data => {
                  console.log('Cancel clicked');
                  addData.selectItemColor = "";
                }
              },
              {
                text: '确定',
                handler: data => {
                  console.log(data);
                  addData.selectItemColor = "";
                  if (this.queryCondition.fund_code === "") {
                    this.common.alertMessage("请先选择基金");
                    return false;
                  }
                  let profileModal = this.modalCtrl.create(IpmCoinSaveSceneModal, {
                    fundCode: this.queryCondition.fund_code,
                    planNo: data,
                    position: position,
                    addData: addData
                  });
                  profileModal.onDidDismiss(data => {
                    if (data && data != "close") {
                      if (data["isSuccess"] && !this.listData.noDatas) {
                        // this.loadDatas();
                      }
                    }
                  });
                  profileModal.present();
                }
              }
            ]
          });
          alert.present();
        }
      }, {
        text: "取消",
        role: 'cancel',
        handler: () => {
          addData.selectItemColor = "";
        }
      }];

      let actionSheet = this.actionSheetCtrl.create({
        title: "",
        buttons: buttons
      });

      actionSheet.present();
    }
  }


  /**
   * 切换横竖屏
   */
  setShowByLandscape(type) {
    if (!this.showByLandscape && type === 2) {
      return false
    }
    this.showByLandscape = !this.showByLandscape;
    if (this.showByLandscape) {
      this.statusBar.hide();

      let child = document.getElementById("circulateContent").getElementsByClassName("scroll-content")[0];
      child["style"]["-webkit-transform"] = "rotate(90deg)";
      child["style"]["-webkit-transform-origin"] = "top";
      child["style"].height = this.contentWidth + "px";
      child["style"].width = document.getElementById("circulateContent").offsetHeight + "px";
      child["style"].zIndex = "99999";
      this.scrollContentMarginTop = child["style"].marginTop;
      child["style"].marginTop = document.getElementById("circulateContent").offsetHeight / 2 + "px";
      child["style"].marginLeft = (this.contentWidth - document.getElementById("circulateContent").offsetHeight / 2) + "px";

      let circulateContent = document.getElementById("circulateContent").offsetHeight;

      //试算结果
      document.getElementById("TrialCalculationResult_ColLeft").style.height = this.contentWidth + "px";
      document.getElementById("TrialCalculationResult_ColRight").style.height = this.contentWidth + "px";
      document.getElementById("TrialCalculationResult_ColRight").style.marginTop = 0 - this.contentWidth + "px";
      document.getElementById("TrialCalculationResult_ColLeft").style.maxWidth = "25%";
      document.getElementById("TrialCalculationResult_ColRight").style.maxWidth = "75%";
      document.getElementById("TrialCalculationResult_ColRight").style.width = "75%";
      document.getElementById("TrialCalculationResult_ColRight").style.marginLeft = "25%";
      document.getElementById("TrialCalculationResult_DataRow").style.width = circulateContent - 10 + "px";

      //模拟情景
      document.getElementById("SimulatedSceneList_ColLeft").style.height = this.contentWidth + "px";
      document.getElementById("SimulatedSceneList_ColRight").style.height = this.contentWidth + "px";
      document.getElementById("SimulatedSceneList_ColRight").style.marginTop = 0 - this.contentWidth + "px";
      document.getElementById("SimulatedSceneList_ColLeft").style.maxWidth = "25%";
      document.getElementById("SimulatedSceneList_ColRight").style.maxWidth = "75%";
      document.getElementById("SimulatedSceneList_ColRight").style.width = "75%";
      document.getElementById("SimulatedSceneList_ColRight").style.marginLeft = "25%";
      document.getElementById("SimulatedSceneList_DataRow").style.width = circulateContent - 10 + "px";

      //分组基金试算
      document.getElementById("StructuredFundTrialCalculationResult_ColLeft").style.height = this.contentWidth + "px";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.height = this.contentWidth + "px";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.marginTop = 0 - this.contentWidth + "px";
      document.getElementById("StructuredFundTrialCalculationResult_ColLeft").style.maxWidth = "25%";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.maxWidth = "75%";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.width = "75%";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.marginLeft = "25%";
      document.getElementById("StructuredFundTrialCalculationResult_DataRow").style.width = circulateContent - 10 + "px";

      //持仓分析
      document.getElementById("PositionTrialCalculationResult_ColLeft").style.height = this.contentWidth + "px";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.height = this.contentWidth + "px";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.marginTop = 0 - this.contentWidth + "px";
      document.getElementById("PositionTrialCalculationResult_ColLeft").style.maxWidth = "25%";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.maxWidth = "75%";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.width = "75%";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.marginLeft = "25%";
      document.getElementById("showByDetail").style.width = circulateContent - 10 + "px";

      //持仓分析（按到期日显示）
      document.getElementById("ShowByMaturityDate_ColLeft").style.height = this.contentWidth + "px";
      document.getElementById("ShowByMaturityDate_ColRight").style.height = this.contentWidth + "px";
      document.getElementById("ShowByMaturityDate_ColRight").style.marginTop = 0 - this.contentWidth + "px";
      document.getElementById("ShowByMaturityDate_ColLeft").style.maxWidth = "30%";
      document.getElementById("ShowByMaturityDate_ColRight").style.maxWidth = "70%";
      document.getElementById("ShowByMaturityDate_ColRight").style.width = "70%";
      document.getElementById("ShowByMaturityDate_ColRight").style.marginLeft = "30%";
      document.getElementById("showByMaturityDate").style.width = circulateContent - 10 + "px";

    } else {
      this.statusBar.show();
      this.plt.ready().then(() => {
        if (this.showByLandscape == false) {
          this.statusBar.show();
        }
      });

      let child = document.getElementById("circulateContent").getElementsByClassName("scroll-content")[0];
      child["style"]["-webkit-transform"] = "rotate(0deg)";
      child["style"].marginTop = this.scrollContentMarginTop;
      child["style"].marginBottom = "0px";
      child["style"].height = "auto";
      child["style"].width = "auto";
      child["style"].marginLeft = "0px";

      //试算结果
      document.getElementById("TrialCalculationResult_DataRow").style.width = this.contentWidth + "px";
      document.getElementById("TrialCalculationResult_ColLeft").style.height = this.fundLeftHeight + "px";
      document.getElementById("TrialCalculationResult_ColRight").style.height = this.fundRightHeight + "px";
      document.getElementById("TrialCalculationResult_ColRight").style.marginTop = "-1px";
      document.getElementById("TrialCalculationResult_ColLeft").style.maxWidth = "33%";
      document.getElementById("TrialCalculationResult_ColRight").style.maxWidth = "67%";
      document.getElementById("TrialCalculationResult_ColRight").style.marginLeft = "33%";

      //模拟情景
      document.getElementById("SimulatedSceneList_DataRow").style.width = this.contentWidth + "px";
      document.getElementById("SimulatedSceneList_ColLeft").style.height = this.fundLeftHeight + "px";
      document.getElementById("SimulatedSceneList_ColRight").style.height = this.fundRightHeight + "px";
      document.getElementById("SimulatedSceneList_ColRight").style.marginTop = "-1px";
      document.getElementById("SimulatedSceneList_ColLeft").style.maxWidth = "33%";
      document.getElementById("SimulatedSceneList_ColRight").style.maxWidth = "67%";
      document.getElementById("SimulatedSceneList_ColRight").style.marginLeft = "33%";

      //分组基金试算
      document.getElementById("StructuredFundTrialCalculationResult_DataRow").style.width = this.contentWidth + "px";
      document.getElementById("StructuredFundTrialCalculationResult_ColLeft").style.height = this.fundLeftHeight + "px";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.height = this.fundRightHeight + "px";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.marginTop = "-1px";
      document.getElementById("StructuredFundTrialCalculationResult_ColLeft").style.maxWidth = "33%";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.maxWidth = "67%";
      document.getElementById("StructuredFundTrialCalculationResult_ColRight").style.marginLeft = "33%";

      //持仓分析
      document.getElementById("showByDetail").style.width = this.contentWidth + "px";
      document.getElementById("PositionTrialCalculationResult_ColLeft").style.height = this.fundLeftHeight + "px";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.height = this.fundRightHeight + "px";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.marginTop = "-1px";
      document.getElementById("PositionTrialCalculationResult_ColLeft").style.maxWidth = "50%";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.maxWidth = "50%";
      document.getElementById("PositionTrialCalculationResult_ColRight").style.marginLeft = "50%";

      //持仓分析（按到期日显示）
      document.getElementById("showByMaturityDate").style.width = this.contentWidth + "px";
      document.getElementById("ShowByMaturityDate_ColLeft").style.height = this.fundLeftHeight + "px";
      document.getElementById("ShowByMaturityDate_ColRight").style.height = this.fundRightHeight + "px";
      document.getElementById("ShowByMaturityDate_ColRight").style.marginTop = "-1px";
      document.getElementById("ShowByMaturityDate_ColLeft").style.maxWidth = "50%";
      document.getElementById("ShowByMaturityDate_ColRight").style.maxWidth = "50%";
      document.getElementById("ShowByMaturityDate_ColRight").style.marginLeft = "50%";


    }
  }

}


/**
 * 数据显示格式化管道
 */
@Pipe({name: 'formatDataPipe'})
export class FormatDataPipe implements PipeTransform {

  constructor(public common: Common) {}

  transform(exponent: string, params: any): string {
    // console.log(params, exponent);
    let returnData = "";

    if (exponent) {
      if (exponent == "-") {
        return exponent;
      } else {
        let exp = parseFloat(exponent);
        let val = 1 / parseFloat(params.accuracy);
        let fixed = params.accuracy.split(".")[1].length;
        let result = (Math.round(exp * val) / val).toFixed(fixed);

        let target = _.toString(result);
        let fix = "";
        if (target.indexOf("-") > -1) {
          fix = "-";
          target = _.replace(target, "-", "");
        }
        let temp = target.split(".");
        if (temp[0]) {
          let length = temp[0].length;
          let remainder = length % 3;
          let mark = remainder == 0 ? remainder : remainder - 1;
          for (var i = length - 3; i > mark; i -= 3) {
            returnData = "," + temp[0].substr(i, 3) + returnData;
          }
          returnData = fix + temp[0].substr(0, remainder == 0 ? 3 : remainder) + returnData;
          if (temp[1]) {
            returnData = returnData + "." + temp[1];
            if (temp[1].length == 1) {
              returnData = returnData + "0";
            }
          } else {
            let accuracyNum = params.accuracy.split(".")[1].length;
            returnData = returnData + ".";
            for (let zeroIndex = 0; zeroIndex < accuracyNum; zeroIndex++) {
              returnData = returnData + "0";
            }
          }
        }

        return returnData;
      }
    } else {
      return "";
    }
  }
}
